#include "string.h"

void int_to_ascii(int n, char str[]) {
    int i = 0, sign = n;
    if (n < 0)
        n = -n;
    do {
        str[i++] = (n % 10) + '0';
    } while ((n /= 10) > 0);
    if (sign < 0)
        str[i++] = '-';

    str[i++] = '\0';

    reverse(str);
}

void hex_to_ascii(int n, char str[]) {
    append(str, '0');
    append(str, 'X');
    char zeros = 0;

    int tmp, i;
    for (i = 28; i > 0; i -= 4) {
        tmp = (n >> i) & 0xF;
        if (tmp == 0 && zeros == 0)
            continue;
        zeros = 1;
        if (tmp >= 0xA)
            append(str, tmp - 0xA + 'a');
        else
            append(str, tmp + '0');
    }
}

void reverse(char str[]) {
    int c;
    for (int i = 0, j = strlen(str) - 1; i < j; i++, j--) {
        c = str[i];
        str[i] = str[j];
        str[j] = c;
    }
}
int strlen(char s[]) {
    int i = 0;
    while (s[i] != '\0') {
        i++;
    }
    return i;
}
void backspace(char s[]) {
    int length = strlen(s);
    s[length - 1] = '\0';
}
void append(char s[], char n) {
    int length = strlen(s);
    s[length] = n;
    s[length + 1] = '\0';
}
int strcmp(char s1[], char s2[]) {
    int i;
    for (i = 0; s1[i] == s2[i]; i++) {
        if (s1[i] == '\0') {
            break;
        }
    }
    return s1[i] - s2[i];
}

// void testCode() {
//     char s1[] = "abc";
//     char s2[] = "abc";
//     printf("%s value=%d \n", "s1 == s2", strcmp(s1, s2));
//     // should be abcdef
//     append(s1, 'd');
//     append(s1, 'e');
//     append(s1, 'f');
//     printf("append %s \n", s1);

//     // should be abcde
//     printf("backspace %s lenght=%d\n", s1, strlen(s1));
//     // should be 5
//     printf("strlen %d\n", strlen(s1));
//     // should be edcba
//     reverse(s1);
//     printf("reverse %s\n", s1);

//     // should be 123
//     char str[10];
//     int_to_ascii(123, str);
//     printf("int_to_ascii: %s\n", str);
//     // should be -123
//     int_to_ascii(-123, str);
//     printf("int_to_ascii: %s\n", str);
// }